Ext.define('FDetailForm', {
    extend: 'FForm',
    alias: 'widget.fdetailform',
    width: 400,
    height: 200,
    showBBar: false,
    masterTable: null,
    detailName: null,
    formAction: null,
    masterIndexName: null,
    detailTable: null,
    detailIndexName: null,
    dataId: null,
    initComponent: function()
    {
        var fieldSet = new Ext.form.FieldSet(
        {
            baseCls: 'x-fieldset-noborder',                
            items: this.formFields
        });
        
        this.formPanel = new Ext.form.FormPanel(
        {
            cls: 'form',
            baseCls: 'x-fieldset-noborder',
            layout: 'form',
            padding: '10 10 10 20',
            width: '100%',
            items: fieldSet
        });
        
        this.formFields = [{
            xtype: 'panel',
            width: '100%',
            flex: 1,
            items: this.formPanel
        }];
    
        this.buttons = [{
                xtype: 'fbutton',
                text: 'Adicionar',
                iconCls: 'button-insert',
                width: 80,
                scope: this,
                handler: this._onBtnAddClick
            },
            {
                xtype: 'fbuttoncancel',
                text: 'Cancelar',
                iconCls: 'fbuttoncancel-icon',
                width: 80,
                scope: this,
                handler: this._onBtnCloseClick
            }];
        
        this.callParent();
    },
    _onBtnAddClick: function()
    {
        var form = this.formPanel.getForm();
        
        if ( !form.isValid() )
        {
            Ext.create('FMessageAlert', {
                msg: 'Preencha corretamente os campos!'
            }).show();
        }
        else
        {
            this.el.mask('Adicionando...');

            var element = document.getElementsByName(this.masterIndexName);
            var masterIdx = null;
            
            for ( var i = 0; i < element.length; i++ )
            {
               var e = element[i];
               masterIdx = e.value;
            }

            form.submit({
                url: this.handlerUrl,
                params: {
                    manager: this.masterTable,
                    formAction: this.formAction,
                    detailName: this.detailName,
                    masterIndexName: this.masterIndexName,
                    masterIndex: masterIdx,
                    detailTable: this.detailTable,
                    detailIndexName: this.detailIndexName,
                    dataId: this.dataId,
                    action: 'add'
                },
                scope: this,
                success: function(form, action)
                {
                    this.obj = Ext.JSON.decode(action.response.responseText);

                    this.el.unmask();
                    this.formPanel.getForm().reset();
                    
                    if ( this.obj.showSuccessMsg )
                    {
                        Ext.create('FMessageSuccess', {
                            msg: this.obj.msg
                        }).show();
                    }

                    this.store.reload();
                    this.doClose();
                },
                failure: function(form, action)
                {
                    this.el.unmask();
                   
                    this.obj = Ext.JSON.decode(action.response.responseText);
                    Ext.create('FMessageError', {
                        msg: this.obj.msg
                    }).show();
                }
            });            
        }
    }
});

Ext.define('FDetail', {
    extend: 'Ext.panel.Panel',
    alias: 'widget.fdetail',
    margin: '18 0 0 0',
    collapsed: true,
    collapsible: true,
    gridColumns: null,
    storeFields: null,
    formFields: null,
    formAction: null,
    masterIndex: null,
    masterIndexName: null,
    masterTable: null,
    detailTable: null,
    detailIndexName: null,
    dataId: null,
    handlerUrl: null,
    gridColumnsConfig: null,
    grid: null,
    initComponent: function()
    {
        var store = Ext.create('Ext.data.JsonStore',
        {
            pageSize: 5,
            autoLoad: true,
            method: 'POST',
            async: true,
            proxy: {
                type: 'ajax',
                url: this.handlerUrl,
                actionMethods: 'POST',
                reader: {
                    type: 'json',
                    root: 'data'
                },
                extraParams: {
                    manager: this.masterTable,
                    formAction: this.formAction,
                    detailName: this.name,
                    detailTable: this.detailTable,
                    detailIndexName: this.detailIndexName,
                    dataId: this.dataId,
                    masterIndexName: this.masterIndexName,
                    masterIndex: '',
                    action: 'list'
                },
                noCache: false
            },
            fields: this.storeFields,
            totalProperty: 'total'
        });
        
        this.gridColumnsConfig = {
            items: [],
            defaults: {
                align: 'center',
                sortable: true,
                hideable: true
            }
        };
        
        for(var i = 0; i < this.storeFields.length; i++ )
        {
            this.gridColumnsConfig.items.push({
                text: this.gridColumns[i].text,
                flex: this.gridColumns[i].flex,
                align: this.gridColumns[i].align,
                sortable: this.gridColumns[i].sortable,
                hideable: this.gridColumns[i].hideable,
                width: this.gridColumns[i].width,
                hidden: !this.gridColumns[i].visible,
                dataIndex: this.storeFields[i]
            });
        }

        this.grid = Ext.create('FGrid',
        {
            store: store,
            columns: this.gridColumnsConfig,
            pageSize: 5,
            showNavBar: false
        });
        
        this.items = [{
                xtype: 'panel',
                layout: 'hbox',
                items: [
                {
                    xtype: 'button',
                    iconAlign: 'top',
                    height: 42,
                    text: 'Adicionar',
                    iconCls: 'button-insert',
                    scope: this,
                    handler: function()
                    {
                        Ext.create('FDetailForm', {
                           formFields: this.formFields,
                           handlerUrl: this.handlerUrl,
                           masterTable: this.masterTable,
                           masterIndexName: this.masterIndexName,
                           detailTable: this.detailTable,
                           detailIndexName: this.detailIndexName,
                           dataId: this.dataId,
                           formAction: this.formAction,
                           detailName: this.name,                           
                           store: store
                        }).show();
                    }
                },
                {
                    xtype: 'button',
                    iconAlign: 'top',
                    height: 42,
                    text: 'Remover',
                    iconCls: 'button-delete',
                    scope: this
                }]
        }, this.grid];            
        
        this.callParent();
    },
    expand: function()
    {                
        this.grid.store.getProxy().extraParams.masterIndex = this.getIndex();
        this.grid.store.reload();
        
        this.callParent();
    },
    getIndex: function()
    {
        var element = document.getElementsByName(this.masterIndexName);

        for( var i = 0; i < element.length; i++ )
        {
           var e = element[i];
           this.masterIndex = e.value;
        }
        
        return this.masterIndex;
    }
});

